<template>
  <div class="app-container">
    <el-card>
      <UpdateExcel :on-success="onSuccess" />
    </el-card>
  </div>
</template>
<script>
import UpdateExcel from '@/components/UpdateExcel'
import { importEmployee } from '@/api/employees'

export default {
  name: 'Import',
  components: {
    UpdateExcel
  },
  data() {
    return {}
  },
  computed: {},
  methods: {
    // 导入excel
    async onSuccess({ header, results }) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      // results.forEach((obj) => {
      //   var userObj = {}
      //   Object.keys(userRelations).forEach((item) => {
      //     userObj[userRelations[item]] = obj[item]
      //   })
      //   arr.push(userObj)
      // })
      // 中文传引文
      var arr = results.map((obj) => {
        var userObj = {}
        header.forEach((item) => {
          if (userRelations[item] === 'timeOfEntry' || userRelations[item] === 'correctionTime') {
            obj[item] = new Date(this.formatDate(obj[item], '/'))
          }
          userObj[userRelations[item]] = obj[item]
        })
        return userObj
      })
      // 批量上传
      await importEmployee(arr)
      this.$message.success('导入excel上传成功！')
      this.$router.back()
    },

    // 当excel中有日期格式的时候，实际转化的值为一个数字，我们需要一个方法进行转化
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 15px;
  ::v-deep .el-card {
    height: 87vh;
  }
}
</style>
